package reflect;

import reflect.annotations.AutoRunClass;

import java.io.File;
import java.net.URISyntaxException;

/**
 * 实例化与当前类Test8在同一个包中被@AutoRunClass标注的类
 */
public class Test8 {
    public static void main(String[] args) throws ClassNotFoundException, URISyntaxException, InstantiationException, IllegalAccessException {
        //获取Test8的类对象
        Class c = Test8.class;
        //获取对象所在包
        String pake = c.getPackage().getName();
        //根据对象获取对象所在路径
        File dir = new File(c.getResource(".").toURI());
        //将对应路径下所有文件都放入文件数组中, 用lambda表达式做筛选
        File[] files = dir.listFiles(f->f.getName().endsWith(".class"));
        //遍历文件数组
        for(File f : files){
            //获取文件名字, 将后缀".class"去掉
            String fName = f.getName().replace(".class","");
            //生成类对象
            Class cls = Class.forName(pake+"."+fName);
            //如果这个类被AutoRunClass注解标注
            if(cls.isAnnotationPresent(AutoRunClass.class)){
                //实例化对象
                Object o = cls.newInstance();
                System.out.println("实例化对象是:"+fName);
                System.out.println(o);
            }
        }
    }
}
